package com.jiuyuan.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jiuyuan.entity.Employee;
import com.jiuyuan.entity.MailConstant;
import com.jiuyuan.entity.MailLog;
import com.jiuyuan.service.IEmployeeService;
import com.jiuyuan.service.IMailLogService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @program: hrms
 * @description:
 * @author: Feng
 * @create: 2023-02-19 09:33
 **/

@Component
public class MailTask {

    @Autowired
    IMailLogService mailLogService;
    @Autowired
    IEmployeeService employeeService;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Scheduled(cron = "0/10 * * * * ?")
    public void mailTast(){
        List<MailLog> mailLogs = mailLogService.list(new QueryWrapper<MailLog>().eq("status", MailConstant.DELEVERING).gt("tryTime", LocalDateTime.now()));
        mailLogs.forEach(mailLog -> {
            //超过次数设置状态
            if(mailLog.getCount()>= MailConstant.MAX_TRY_COUNT){
                mailLogService.update(new UpdateWrapper<MailLog>().eq("id",mailLog.getId()).set("status",MailConstant.FAILURE));
            }
            //数字+1，时间改变
            mailLogService.update(new UpdateWrapper<MailLog>().eq("id",mailLog.getId()).set("count",mailLog.getCount()+1).set("updateTime",LocalDateTime.now()).set("tryTime",LocalDateTime.now().plusMinutes(MailConstant.MAX_TRY_TIME)));

            //获取员工
            Employee emp = employeeService.getEmployeeById(mailLog.getEid()).get(0);
            //消息重试
            rabbitTemplate.convertAndSend(MailConstant.MAIL_EXCHANGE_NAME,MailConstant.MAIL_ROUTING_KEY_NAME,emp,new CorrelationData(mailLog.getMsgId()));

        });
    }
}




































